package org.liam.ltrans.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.*;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.liam.ltrans.pojo.Batchs;
import org.liam.ltrans.pojo.ItemInfo;
import org.liam.ltrans.pojo.LexFile;
import org.liam.ltrans.pojo.Ltrans;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class LtransUtils {

    public void addBOMToCSV(String csvFilePath, String outputFilePath) {
        try {
            // 读取 CSV 文件
            FileInputStream inputStream = new FileInputStream(new File(csvFilePath));
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                // 写入带有 BOM 的内容到输出文件
                FileOutputStream outputStream = new FileOutputStream(outputFilePath, true);
                outputStream.write(0xEF); // BOM 的第一个字节
                outputStream.write(0xBB); // BOM 的第二个字节
                outputStream.write(0xBF); // BOM 的第三个字节
                outputStream.write(buffer, 0, bytesRead);
                outputStream.close();
            }
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void exportCSV(List<List<String>> data, String outputFile) {

        CsvWriter writer = CsvUtil.getWriter(outputFile, CharsetUtil.CHARSET_GBK);
        for (List<String> line : data) {
            String[] array = line.toArray(new String[0]);
            writer.writeLine(array);
        }

    }

    public List<List<String>> getExportExcelData(List<Ltrans> ltrans) {
        List<List<String>> csvData = new ArrayList<>();

        String[] columns = {"#日期", "开料批次", "裁板文件", "图层数量", "材料利用率", "编码", "条形码", "材料", "开料长", "开料宽", "厚度", "订单号", "客户名称", "产品号", "产品名称", "工件名称", "开槽", "打孔分类", "备注", "尺寸判定", "条形码1", "包装号", "批次号"};
        List<String> row0 = Arrays.asList(columns);
        csvData.add(row0);

        //文件层的循环
        for (Ltrans item : ltrans) {
            String name = item.getId();

            List<Batchs> batchNums = item.getBatchNums();
            //批次的循环
            for (Batchs batch : batchNums) {
                String batchNum = batch.getBatchNum();

                List<LexFile> lexFiles = batch.getLexFiles();
                //文件的循环
                for (LexFile fileItem : lexFiles) {
                    String fileName = fileItem.getFileName();
                    String useRate = fileItem.getUseRate();
                    String picNum = fileItem.getPicNum();

                    List<ItemInfo> itemInfos = fileItem.getItemInfos();
                    //信息的循环
                    for (ItemInfo itemInfo : itemInfos) {
                        List<String> infoRow = new ArrayList<>();
                        if (StrUtil.isNotEmpty(name)) {
                            infoRow.add(name);
                            name = null;
                        } else {
                            infoRow.add(null);
                        }
                        if (StrUtil.isNotEmpty(batchNum)) {
                            infoRow.add(batchNum);
                            batchNum = null;
                        } else {
                            infoRow.add(null);
                        }
                        if (StrUtil.isNotEmpty(fileName)) {
                            infoRow.add(fileName);
                            fileName = null;
                        } else {
                            infoRow.add(null);
                        }
                        if (StrUtil.isNotEmpty(picNum)) {
                            infoRow.add(picNum);
                            picNum = null;
                        } else {
                            infoRow.add(null);
                        }
                        if (StrUtil.isNotEmpty(useRate)) {
                            infoRow.add(useRate);
                            useRate = null;
                        } else {
                            infoRow.add(null);
                        }
                        infoRow.add(itemInfo.getEncoding());
                        infoRow.add(itemInfo.getBarcode());
                        infoRow.add(itemInfo.getMaterial());
                        infoRow.add(itemInfo.getCutLength());
                        infoRow.add(itemInfo.getCutWidth());
                        infoRow.add(itemInfo.getThickness());
                        infoRow.add(itemInfo.getOrderNumber());
                        infoRow.add(itemInfo.getCustomerName());
                        infoRow.add(itemInfo.getProductNumber());
                        infoRow.add(itemInfo.getProductName());
                        infoRow.add(itemInfo.getWorkpieceName());
                        infoRow.add(itemInfo.getSlot());
                        infoRow.add(itemInfo.getDrillingCategory());
                        infoRow.add(itemInfo.getNote());
                        infoRow.add(itemInfo.getSizeJudgment());
                        infoRow.add(itemInfo.getBarcode1());
                        infoRow.add(itemInfo.getPackagingNumber());
                        infoRow.add(itemInfo.getBatchNumber());
                        csvData.add(infoRow);
                    }

                }

            }

        }
        return csvData;

    }

    private List<String> getCSVDataRow(List<List<String>> csvData, int rowNum) {
        return csvData.get(rowNum);

    }


//    public List<Ltrans> getPOJO(String baseDirPath) {
//        LtransUtils utils = new LtransUtils();
//        // 定义返回体
//        List<Ltrans> ltrans = new ArrayList<>();
//        //获取全部的目录名称（排序后）
//        String[] sordedDirName = utils.SortDirectories(baseDirPath);
//        for (String dirName : sordedDirName) {
//            utils.dealWithBatchLevel(baseDirPath,dirName, ltrans);
//
//        }
//        return ltrans;
//
//    }


    public String[] sortDirectories(String dirPath) {
        File dir = new File(dirPath);
        String[] list = dir.list();
        Arrays.sort(list, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                // remove non-digit characters
                int o1N = Integer.parseInt(o1.replaceAll("[^0-9]", ""));
                int o2N = Integer.parseInt(o2.replaceAll("[^0-9]", ""));
                return Integer.compare(o1N, o2N);
            }
        });
        return list;

    }

    public String[] getAllBatchNumFromOneDir(String batchDir) {

        //获取批次号
        String[] batchNum = sortDirectories(batchDir);
        return batchNum;

    }

    public void dealWithBatchLevel(String baseDir, String dirName, List<Ltrans> ltrans) throws UnsupportedEncodingException {
        //新建返回对象
        Ltrans ltransitem = new Ltrans();
        //填充文件夹名字（序号）
        ltransitem.setId(dirName);
        //定义批次集合
        List<Batchs> batchs = new ArrayList<>();
        //拼接新的目录
        String loopDir1 = baseDir + File.separator + dirName;
        String[] allBatchNumFromOneDir = getAllBatchNumFromOneDir(loopDir1);
        for (String batchitem : allBatchNumFromOneDir) {
            Batchs batchs1 = new Batchs();
            batchs1.setBatchNum(batchitem);
            dealFileLevel(baseDir, dirName, batchitem, batchs1);
            batchs.add(batchs1);
        }
        ltransitem.setBatchNums(batchs);
        //拼接新的批次号目录
        ltrans.add(ltransitem);
    }

    private static void dealFileLevel(String baseDir, String dirName, String batchitem, Batchs batchs1) throws UnsupportedEncodingException {
        List<LexFile> fileList = new ArrayList<>();
        //拼接fileDir的路径
        String filePath = baseDir + File.separator + dirName + File.separator + batchitem;
        //获取所有的excel文件
        List<File> files = FileUtil.loopFiles(filePath);
        for (File file : files) {
            LexFile item = new LexFile();
            item.setFileName(file.getName());
            dealWithFileCSV(file, item);
            fileList.add(item);
        }
        batchs1.setLexFiles(fileList);
    }

    public static void dealWithFileCSV(File file, LexFile lexFile) throws UnsupportedEncodingException {

        CsvReader reader = CsvUtil.getReader();
        CsvData data = reader.read(file, CharsetUtil.CHARSET_GBK);
        List<CsvRow> rows = data.getRows();
        CsvRow headStr = rows.get(0);
        String picNumStr = headStr.get(9);
        int picNum = Integer.parseInt(picNumStr);
        String rate = headStr.get(8);
        lexFile.setUseRate(rate);
        lexFile.setPicNum(picNumStr);
        //筛选匹配的列数
        List<Integer> collect = rows.stream().filter(row -> row.size() == 3).map(rows::indexOf).collect(Collectors.toList());
        //如果识别的行数与图层不匹配，倒数开始录入
        if (collect.size() != picNum) {
            collect = collect.subList(collect.size() - picNum, collect.size());
        }
        //开始读取图层
        for (int i = 0; i < picNum; i++) {
            dealWithPicLevel(rows, collect, i, lexFile);
        }


    }

    private static void dealWithPicLevel(List<CsvRow> rows, List<Integer> collect, int i, LexFile lexFile) throws UnsupportedEncodingException {
        CsvRow headInfoItem = rows.get(collect.get(i));
        //读取的行数
        String rowNum = headInfoItem.get(2);
        int beginNum = collect.get(i) + 1;
        int endNum = collect.get(i) + Integer.parseInt(rowNum);
        List<ItemInfo> itemInfos = new ArrayList<>();
        //获取的数据项
        List<CsvRow> csvRows = rows.subList(beginNum, endNum + 1);
        //对象封装
        for (CsvRow row : csvRows) {

            //这里是GBK编码的内容
            ItemInfo info = new ItemInfo();
            info.setEncoding(row.get(0));
            info.setBarcode(row.get(1));
            info.setMaterial(row.get(2));
            info.setCutLength(row.get(3));
            info.setCutWidth(row.get(4));
            info.setThickness(row.get(5));
            info.setOrderNumber(row.get(6));
            info.setCustomerName(row.get(7));
            info.setPackagingNumber(row.get(8));
            info.setProductName(row.get(9));
            info.setWorkpieceName(row.get(10));
            info.setSlot(row.get(11));
            info.setDrillingCategory(row.get(12));
            info.setNote(row.get(13));
            info.setSizeJudgment(row.get(14));
            info.setBarcode1(row.get(15));
            info.setPackagingNumber(row.get(16));
            info.setBatchNumber(row.get(17));
            itemInfos.add(info);
        }
        lexFile.setItemInfos(itemInfos);
    }
}
